﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;

namespace HT.Future.FileServer.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class UserController : ControllerBase
    {

        /// <summary>
        /// 保存用户头像
        /// </summary>
        /// <param name="dic"></param>
        /// <param name="host"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<string> Index([FromBody] Dictionary<string, string> dic, [FromServices] IWebHostEnvironment host)
        {
            var data = dic["item1"];
            var name = dic["item2"];
            var filename = name + ".jpg";
            var dirPath = Path.Combine(host.WebRootPath, "faces");
            var filepath = Path.Combine(dirPath, filename);
            if (!Directory.Exists(dirPath)) Directory.CreateDirectory(dirPath);
            using HttpClient client = new HttpClient();
            var img = await client.GetByteArrayAsync(data);
            using FileStream file = new FileStream(filepath, FileMode.OpenOrCreate, FileAccess.Write);
            file.Write(img, 0, img.Length);
            return filename;
        }
    }
}
